<template>
    <div class="main">
        <div class="filter-container">
            <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseGoods">添加商品</el-button>
            <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseGoodsPackage" plain>添加套餐</el-button>
            <el-button v-if="form.crushGoodsList.length>8"  type="success" class="filter-item fr" @click="save">保 存</el-button>
        </div>
        <el-form :model="form" size="medium" ref="form" label-width="0px">
            <el-table :data="form.crushGoodsList" v-loading="listLoading" element-loading-text="给我一点时间">
                <el-table-column align="center" type="expand" width="100">
                    <template slot-scope="scope" v-if="scope.row.type===1">
                        <el-table :data="scope.row.goodsAttrList" highlight-current-row border>
                            <el-table-column align="center" label="图库" width="100" fixed>
                                <template slot-scope="$scope">
                                    <div class="avatar-uploader">
                                      <label class="el-upload el-upload-text" style="width: 80px; height: 80px; line-height: 82px">
                                          <img v-if="$scope.row.skuImage" :src="$scope.row.skuImage" alt="">
                                          <!-- <i v-if="!$scope.row.skuImage" class="el-icon-plus avatar-uploader-icon"></i>
                                          <input type="file" class="el-upload__input" accept="image/*" @change="uploadAttrImg($scope.row, $event)"> -->
                                      </label>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column v-for="(item, index) in [{id: 'attrId1',prop: 'attrValue1'},{id:'attrId2',prop: 'attrValue2'},]" v-show="scope.row.goodsAttrList[0][item.id]" :key="index" align="center" :label="'属性值'+(index+1)" :prop="item.prop" min-width="100px">
                            </el-table-column>
                            <el-table-column align="center" label="商品原价（兰密价）" min-width="70px"  prop="priceOld">
                              <!-- <template slot-scope="$scope">
                                <el-form-item :prop="'crushGoodsList.'+scope.$index+'.goodsAttrList['+$scope.$index+'].price'" :rules="commonRules.price" style="margin: 30px 0">
                                    <el-input type="number" v-model="$scope.row.marketValue" style="width: 100%"></el-input>
                                </el-form-item>
                              </template> -->
                            </el-table-column>
                            <el-table-column align="center" label="会员价" min-width="70px">
                              <template slot-scope="$scope">
                                <el-form-item :prop="'crushGoodsList['+scope.$index+'].goodsAttrList['+$scope.$index+'].price'" :rules="rules.price" style="margin: 30px 0">
                                    <el-input type="number" placeholder="小于商品原价"  v-model="$scope.row.price" style="width: 100%" ></el-input>
                                </el-form-item>
                              </template>
                            </el-table-column>
                            <el-table-column align="center" label="商品原佣金" min-width="70px" prop="maximumCommissionOld">
                            </el-table-column>
                            <el-table-column align="center" label="会员最高佣金" min-width="70px">
                              <template slot-scope="$scope">
                                <el-form-item :prop="'crushGoodsList['+scope.$index+'].goodsAttrList['+$scope.$index+'].maximumCommission'" :rules="rules.maximumCommission" style="margin: 30px 0">
                                    <el-input type="number" placeholder="小于最高佣金" v-model="$scope.row.maximumCommission" style="width: 100%"></el-input>
                                </el-form-item>
                              </template>
                            </el-table-column>
                            <el-table-column align="center" label="库存数" prop="totalSkuNumber" min-width="86px">
                              <template slot-scope="$scope">
                                {{$scope.row.totalSkuNumber}}
                                <!-- <div v-if="!$scope.row.skuNumber" style="color: red">库存不足</div> -->
                              </template>
                            </el-table-column>
                            <!-- <el-table-column align="center" label="是否上架" width="80">
                              <template slot-scope="$scope">
                                <el-switch
                                  v-model="$scope.row.upshelf"
                                  active-color="#13ce66"
                                  inactive-color="#ff4949"
                                  :active-value="1"
                                  :inactive-value="0">
                                </el-switch>
                              </template>
                            </el-table-column> -->
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="类别"  prop="typeName">
                </el-table-column>
                <el-table-column align="center" label="商品id"  prop="goodsId">
                </el-table-column>
                <el-table-column align="center" label="商品名称" prop="goodsName">
                </el-table-column>
                <el-table-column align="center" label="操作" width="120" fixed="right">
                  <template slot-scope="scope">
                      <a href="javascript: void(0);" class="el-icon-remove" @click="delItem(scope.row, scope.$index)"></a>
                  </template>
                </el-table-column>
            </el-table>
            <div style="text-align: center; padding: 20px">
              <el-button type="success" @click="save" :loading="btnLoading">保 存</el-button>
            </div>
        </el-form>
    </div>
</template>
<script>
  import differenceBy from 'lodash/differenceBy';
  import { goodsCheck } from '@/api/activity/fullReduce'

  export default {
    name: 'activityMemberGoodList',
    props: {
      id: { default: '' }
    },
    data() {
      return {
        listLoading: false,
        listQuery: {
          vipdayId: this.id
        },
        form: {
          crushGoodsList: []
        },
        deleteIds:[],
        btnLoading: false,
        index1: '',
        index2: '',
        rules:{
          'price': [
            { required: true, message: '不能为空', trigger: 'change' },
            {validator: (rule, value, callback, source, options) => {
              let a = ''
              for(let key in source) {
                 a = key.replace('price', 'priceOld')
              }
              let b = a.split('[')
              //取对应的下标
              let c = b[1].split(']')[0]
              let d = b[2].split(']')[0]
              if(value>this.form.crushGoodsList[c].goodsAttrList[d].priceOld) {
                callback(new Error('不能大于商品原价'))
              } else {
                callback()
              }
            }},
            {pattern: /(^[1-9](\d{1,7})?(\.[0-9]{1,2})?$)|(^[0-9]\.[0-9]([0-9])?$)|0/, message: '须大于等于0,小于100000000且最多保留两位小数', trigger: 'change'}
          ],
          'maximumCommission': [
            { required: true, message: '不能为空', trigger: 'change' },
            {validator: (rule, value, callback, source, options) => {
              let a = ''
              for(let key in source) {

                 a = key.replace('maximumCommission', 'maximumCommissionOld')
              }
              let b = a.split('[')
              //取对应的下标
              let c = b[1].split(']')[0]
              let d = b[2].split(']')[0]
              if(value > this.form.crushGoodsList[c].goodsAttrList[d].maximumCommissionOld) {
                callback(new Error('不能大于最高佣金'))
              } else {
                callback()
              }
            }},
            {pattern: /(^[1-9](\d{1,7})?(\.[0-9]{1,2})?$)|(^[0-9]\.[0-9]([0-9])?$)|0/, message: '须大于等于0,小于100000000且最多保留两位小数', trigger: 'change'}
          ]
        }
      }
    },
    created(){
      this.getList();
    },
    methods: {
      async checkActivity(val, idList, type) {
        const goodsType = type === 'single' ? 'goodsId' : 'packageId'
        let newArr = []
        const arr = val.map(async(item, index) => {
          if (!idList.includes(item[goodsType])) {
            const param = {
              id: item[goodsType],
              checkList: [1, 2, 3, 4] // 互斥类型
            }
            const res = await goodsCheck(param)
            if (res.status === 200) {
              newArr.push(item)
              return item
            }
          } else {
              newArr.push(item)
              return item
          }
        })
        let result = await Promise.all(arr)
        return result
      },
      aaa(index1, index2) {
        this.index1 = index1
        this.index2 = index2
        console.log(index1, index2)
      },
      getList(){
        this.listLoading = true;
        this.request({
          url: '/vip-day/web-manage/goods-page/get',
          method: 'get',
          params: this.listQuery
        }).then(({data}) => {
          // console.log(data)
          if(data.length>0){
            this.form.crushGoodsList = data
          }
          this.listLoading = false
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        });
      },
      // 选择商品
      chooseGoods(){
        let idList = []
        let newArr = []
        let goods= this.form.crushGoodsList.filter(item => item.type === 1).map(i => {
          idList.push(i.goodsId)
          return {
            goodsId: i.goodsId,
            name: i.goodsName
          }
        })
        this.goodsChoose({}, goods).then(async val => {
          // 检验活动重复
          newArr = await this.checkActivity(val, idList, 'single')
          newArr = newArr.filter(item => {
            return item !== undefined
          })
          // 校验end
          val = newArr
          let goodsList = this.form.crushGoodsList.filter(item => item.type ===1)
          let needDelGoods = differenceBy(goodsList, val, 'goodsId')
          let needAddGoods = differenceBy(val, goodsList, 'goodsId')
          console.log(needDelGoods)
          console.log(needAddGoods)
          needDelGoods.map(item => {
            if(item.id){
              this.deleteIds.push(item.id)
            }
          })
          this.form.crushGoodsList = (differenceBy(this.form.crushGoodsList, needDelGoods, 'goodsId'))
          let timeGoods = []
          needAddGoods.map((item) => {
            this.request({
              url: '/bsnl-product/goods/details',
              method: 'get',
              params: { id: item.id }
            }).then(({data}) => {
              let goodsData = data
                if(goodsData.goodsAttr.length>0) {
                  goodsData.goodsAttr.forEach(item => {
                    item.priceOld = item.price,
                    item.maximumCommissionOld = item.maximumCommission
                  })
                }
                this.form.crushGoodsList.push({
                  goodsId: goodsData.goods.goodsId,
                  goodsName: goodsData.goods.name,
                  type: 1,
                  typeName: '单品',
                  packageId: null,
                  id: '',
                  goodsAttrList: goodsData.goodsAttr
                })
            })
          })
        }).catch(err => {
          this.form.crushGoodsList = this.form.crushGoodsList.filter(item => item.type !==1)
        });
      },
      // 选择套餐
      chooseGoodsPackage(){
        let selected = this.form.crushGoodsList.filter(item=>item.type===2).map(item => {
          return {
            packageId: item.packageId,
            name: item.goodsName
          }
        })
        this.packageChoose({}, selected).then(val => {
          let packageList = this.form.crushGoodsList.filter(item => item.type ===2)
          let needDelPackage = differenceBy(packageList, val, 'packageId')
          let needAddPackage = differenceBy(val, packageList, 'packageId')
          needDelPackage.map(item => {
            if(item.id){
              this.deleteIds.push(item.id)
            }
          })
          this.form.crushGoodsList = (differenceBy(this.form.crushGoodsList, needDelPackage, 'packageId'))
          needAddPackage.map((item) => {
            this.form.crushGoodsList.push({
              goodsId: item.packageId,
              goodsName: item.name,
              type: 2,
              typeName: '套餐',
              packageId: item.packageId,
              id: '',
              goodsAttrList: []
            })
          })
        })
      },
      delItem(row, index){
        this.$confirm(`确定要删除吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(row.id){
            this.deleteIds.push(row.id)
            this.form.crushGoodsList.splice(index, 1);
          }else{
            this.form.crushGoodsList.splice(index, 1);
          }
        }).catch(err => {
          console.log(err)
        })
      },
      save(){
        this.$refs.form.validate(valid => {
          if (!valid) {
            return false;
          }
          let  list = {
            vipdayGoodsList: this.form.crushGoodsList,
            vipdayId: this.id
          }
          this.btnLoading = true
          if(this.deleteIds.length>0) {
            this.request({
              url: '/vip-day/web-manage/goods/delete',
              method: 'delete',
              data:{ ids: this.deleteIds}
            }).then(() => {
              this.request({
                url: '/vip-day/web-manage/goods/create',
                method: 'post',
                data: list
              }).then(() => {
                this.$message.success('保存成功')
                this.btnLoading = false
                this.$router.back()
              }).catch(err => {
                this.btnLoading = false
                console.log(err)
              })
            }).catch(err => {
              console.log(err);
            });
          } else {
            this.request({
              url: '/vip-day/web-manage/goods/create',
              method: 'post',
              data: list
            }).then(() => {
              this.$message.success('保存成功')
              this.btnLoading = false
              this.$router.back()
            }).catch(err => {
              this.btnLoading = false
              console.log(err)
            })
          }
        })
      }
    }
  }
</script>
<style lang="scss">
    @import "../../../../styles/mixin";
    .el-table__expanded-cell[class*=cell] {
        padding: 20px;
    }
    .el-table__body .el-select,
    .el-table__body .el-input{
        width: 100% !important;
    }
    .time-goods-list{
        @include scrollbar();
        max-height: 300px;
    }
</style>
